/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.booting.balancer4j;

import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * This FailOverLoadBalancer will failover to use next processor when an exception occurred
 * <p/>
 * This implementation mirrors the logic in the async variation
 * as the failover load balancer is a specialized pipeline. So the trick is to keep doing the same as the
 * pipeline to ensure it works the same and the async routing engine is flawless.
 */
public class FailOverLoadBalancer extends LoadBalancerSupport {

    private static final Logger LOG = LoggerFactory.getLogger(FailOverLoadBalancer.class);

    @Getter
    @Setter
    private List<Class<?>> exceptions;
    @Getter
    @Setter
    private boolean roundRobin;
    @Getter
    @Setter
    private boolean sticky;
    @Getter
    @Setter
    private int maximumFailoverAttempts = -1;

    // stateful statistics
    private final AtomicInteger counter = new AtomicInteger(-1);
    private final AtomicInteger lastGoodIndex = new AtomicInteger(-1);
    private final ExceptionFailureStatistics statistics = new ExceptionFailureStatistics();

    public FailOverLoadBalancer() {
        this.exceptions = null;
    }

    public FailOverLoadBalancer(List<Class<?>> exceptions) {
        this.exceptions = exceptions;

        // validate its all exception types
        for (Class<?> type : exceptions) {
            if (!Throwable.class.isAssignableFrom(type)) {
                throw new IllegalArgumentException("Class is not an instance of Throwable: " + type);
            }
        }

        statistics.init(exceptions);
    }

    public int getLastGoodIndex() {
        return lastGoodIndex.get();
    }

    /**
     * Should the given failed Action failover?
     *
     * @param action the action that failed
     * @return <tt>true</tt> to failover
     */
    protected boolean shouldFailOver(Action action) {
        if (action == null) {
            return false;
        }

        boolean answer = false;

        if (action.getException() != null) {
            if (exceptions == null || exceptions.isEmpty()) {
                // always failover if no exceptions defined
                answer = true;
            } else {
                for (Class<?> exception : exceptions) {
                    // will look in exception hierarchy
                    if (action.getException(exception) != null) {
                        answer = true;
                        break;
                    }
                }
            }

            if (answer) {
                // record the failure in the statistics
                statistics.onHandledFailure(action.getException());
            }
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Should failover: {} for action {}", answer, action);
        }

        return answer;
    }

    public boolean process(final Action exchange, final Callback callback) {
        Candidate[] processors = doGetCandidates();
        return false;
    }


    protected class State {

        final Action action;
        final Callback callback;
        final Candidate[] processors;
        int index;
        int attempts;
        // use a copy of the original exchange before failover to avoid populating side effects
        // directly into the original exchange
        Action copy;

        public State(Action action, Callback callback, Candidate[] processors) {
            this.action = action;
            this.callback = callback;
            this.processors = processors;

            // get the next processor
            if (isSticky()) {
                int idx = lastGoodIndex.get();
                index = Math.max(idx, 0);
            } else if (isRoundRobin()) {
                index = counter.updateAndGet(x -> ++x < processors.length ? x : 0);
            }
            LOG.trace("Failover starting with endpoint index {}", index);
        }

        public void run() {
            if (copy != null && !shouldFailOver(copy)) {
                // remember last good index
                lastGoodIndex.set(index);
                // and copy the current result to original so it will contain this result of this eip
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Failover complete for exchangeId: {} >>> {}", action, action);
                }
                callback.done(false);
                return;
            }

            // can we still run
            if (!isRunAllowed()) {
                LOG.trace("Run not allowed, will reject executing exchange: {}", action);
                if (action.getException() == null) {
                    action.setException(new RejectedExecutionException());
                }
                // we cannot process so invoke callback
                callback.done(false);
                return;
            }

            if (copy != null) {
                attempts++;
                // are we exhausted by attempts?
                if (maximumFailoverAttempts > -1 && attempts > maximumFailoverAttempts) {
                    LOG.debug("Breaking out of failover after {} failover attempts", attempts);
                    callback.done(false);
                    return;
                }

                index++;
                counter.incrementAndGet();
            }

            if (index >= processors.length) {
                // out of bounds
                if (isRoundRobin()) {
                    LOG.trace("Failover is round robin enabled and therefore starting from the first endpoint");
                    index = 0;
                    counter.set(0);
                } else {
                    // no more processors to try
                    LOG.trace("Breaking out of failover as we reached the end of endpoints to use for failover");
                    callback.done(false);
                    return;
                }
            }

            // try again but copy original exchange before we failover
            Candidate candidate = processors[index];

            // process the exchange
            LOG.debug("Processing failover at attempt {} for {}", attempts, copy);
            candidate.process(copy, doneSync -> REACTIVE.schedule(this::run));
        }

    }


    public ExceptionFailureStatistics getExceptionFailureStatistics() {
        return statistics;
    }

    public void reset() {
        // reset state
        lastGoodIndex.set(-1);
        counter.set(-1);
        statistics.reset();
    }

}
